<template>
  <div class="flex space-x-2 mb-2">
    <Dropdown
      v-model="curDcitCategory"
      :options="dictCategory"
      optionLabel="name"
      @change="_getDictList()"
    />
    <Button icon="far fa-plus" label="新增" class="p-button-primary p-button-sm" @click="toggle" />
    <OverlayPanel ref="op" :showCloseIcon="true">
      <InputText type="text" v-model="newValue" placeholder="字典名称" class="p-inputtext-sm !mr-2" />
      <Button
        icon="fas fa-check"
        label="确定"
        class="p-button-primary p-button-sm"
        @click="_addDict"
      />
    </OverlayPanel>
  </div>
  <DataTable
    :value="dicts"
    :resizableColumns="true"
    columnResizeMode="fit"
    showGridlines
    responsiveLayout="scroll"
    class="p-datatable-sm"
  >
    <Column field="did" header="字典id"></Column>
    <Column field="value" header="字典类型"></Column>
    <Column header="操作">
      <template #body="props">
        <Button
          v-if="props.data.children"
          icon="far fa-eye"
          class="p-button-rounded p-button-outlined !mr-2"
          @click="_showChildDict(props.data.children)"
          title="查看子字典"
        />
        <Button
          icon="far fa-plus"
          class="p-button-rounded p-button-success p-button-outlined !mr-2"
          @click="showChild($event, props.data.did)"
          title="新增子字典"
        />
        <Button
          icon="far fa-trash-can"
          class="p-button-rounded p-button-danger p-button-outlined"
          @click="_deleteDict(props.data.value, props.data.did)"
          title="删除字典"
        />
      </template>
    </Column>
  </DataTable>
  <OverlayPanel ref="op_add" :showCloseIcon="true">
    <InputText type="text" v-model="newValue" placeholder="子字典名称" class="p-inputtext-sm !mr-2" />
    <Button
      icon="fas fa-check"
      label="确定"
      class="p-button-primary p-button-sm"
      @click="_addChildDict"
    />
  </OverlayPanel>
  <Dialog header="子字典" :modal="true" v-model:visible="showChildDict">
    <DataTable
      :value="dictChildren"
      :resizableColumns="true"
      columnResizeMode="fit"
      showGridlines
      responsiveLayout="scroll"
      class="p-datatable-sm"
    >
      <Column field="did" header="字典id"></Column>
      <Column field="value" header="字典类型"></Column>
      <Column header="操作">
        <template #body="props">
          <Button
            icon="far fa-trash-can"
            class="p-button-rounded p-button-danger p-button-outlined"
            @click="_deleteDict(props.data.value, props.data.did)"
            title="删除字典"
          />
        </template>
      </Column>
    </DataTable>
  </Dialog>
  <Paginator :rows="10" :totalRecords="totalRecords" @page="_getDictList($event.page + 1)" />
</template>

<script lang="ts">
export default defineComponent({
  name: 'DictManage'
})
</script>

<script lang="ts" setup>
import { computed, defineComponent, ref } from 'vue'
import { useStore } from 'vuex'
import { useToast } from 'primevue/usetoast'
import { useConfirm } from 'primevue/useconfirm'
import { getDictList, deleteDict, addDict, getDictCategoryList } from '@/api/admin/dict'

import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Button from 'primevue/button'
import OverlayPanel from 'primevue/overlaypanel'
import Paginator from 'primevue/paginator'
import InputText from 'primevue/inputtext'
import Dropdown from 'primevue/dropdown'
import Dialog from 'primevue/dialog'

let toast = useToast()
let confirm = useConfirm()
const store = useStore()

const dicts = ref<Dict[]>()
const op = ref()
const op_add = ref()
const newValue = ref('')
const curDcitCategory = ref<any>()
const totalRecords = ref(1)
const curPage = ref(1)
const addDid = ref(0)
const dictChildren = ref<Dict[]>()
const showChildDict = ref(false)

function toggle(event: Event) {
  op.value.toggle(event)
}

async function showChild(event: Event, did: number) {
  addDid.value = did
  await op_add.value.hide()
  op_add.value.show(event)
}

function _showChildDict(children: Dict[]) {
  dictChildren.value = children
  showChildDict.value = true
}

function _addDict() {
  if (newValue.value.trim() === '') {
    toast.add({ severity: 'error', summary: '提示', detail: '字典类型不能为空', life: 2000 })
    return
  }
  addDict(curDcitCategory.value.dcid, newValue.value)
    .then(() => {
      toast.add({ severity: 'success', summary: '添加成功', detail: `成功添加${newValue.value}`, life: 3000 })
      newValue.value = ''
      _getDictList()
    })
    .catch(err => {
      toast.add({ severity: 'error', summary: '添加失败', detail: err.data.msg, life: 3000 })
    })
}

function _addChildDict() {
  if (newValue.value.trim() === '') {
    toast.add({ severity: 'error', summary: '提示', detail: '字典类型不能为空', life: 2000 })
    return
  }
  addDict(curDcitCategory.value.dcid, newValue.value, addDid.value)
    .then(() => {
      toast.add({ severity: 'success', summary: '添加成功', detail: `成功添加${newValue.value}`, life: 3000 })
      newValue.value = ''
      _getDictList()
    })
    .catch(err => {
      toast.add({ severity: 'error', summary: '添加失败', detail: err.data.msg, life: 3000 })
    })
}

function _deleteDict(category: string, dcid: number) {
  confirm.require({
    message: `删除字典类型可能会导致程序无法运行`,
    header: `删除${category}`,
    acceptLabel: '确定',
    rejectLabel: '取消',
    icon: 'far fa-bookmark-slash',
    acceptClass: 'p-button-danger',
    accept: () => {
      deleteDict(dcid)
        .then(() => {
          toast.add({ severity: 'success', summary: '删除成功', detail: `已删除${category}`, life: 3000 })
          _getDictList()
        })
        .catch(err => {
          toast.add({ severity: 'error', summary: '删除失败', detail: err.data.msg, life: 3000 })
        })
    }
  })
}

async function _getDictList(page?: number) {
  if (!store.state.dict_category) {
    await getDictCategoryList()
      .then(res => {
        store.commit('setDictCategoryList', res.data)
      })
      .catch(err => {
        toast.add({ severity: 'error', summary: '获取字典类型列表失败', detail: err.data.msg, life: 3000 })
      })
  }
  if (!curDcitCategory.value) {
    curDcitCategory.value = store.state.dict_category[0]
  }

  getDictList(curDcitCategory.value.dcid, page ? page : 1)
    .then(res => {
      dicts.value = res.data.list
      totalRecords.value = res.data.total
      curPage.value = page ? page : 1
    })
    .catch(err => {
      toast.add({ severity: 'error', summary: '获取字典列表失败', detail: err.data.msg, life: 3000 })
      dicts.value = []
      totalRecords.value = 1
      curPage.value = 1
    })
}

const dictCategory = computed(() => {
  return store.state.dict_category
})

_getDictList()
</script>